/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddTask.java
 *
 * Created on Jun 9, 2009, 10:19:50 AM
 */
package OtherForms;

import Helpers.GlobalVariables;
import MyTable.*;
import MyTable.MyTableModel;
import Persistences.*;
import Repositories.*;
import java.awt.Color;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;

/**
 *
 * @author letuan
 */
public class DlgAddSchedule extends javax.swing.JDialog {

    /** Creates new form AddTask */
    private boolean _Success = false;
    private DefaultListModel model;
    private static int PREFERRED_SIZE = 12;
    private Date DateSchedule;
    private Scheduling SelectedSchedule;

    /**
     * constructors
     * @param parent
     * @param modal
     * @param task
     */
    public DlgAddSchedule(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public DlgAddSchedule(java.awt.Frame parent, boolean modal, Date date) {
        super(parent, modal);
        initComponents();
        DateSchedule = date;
        LoadScheduling();
    }

    public void LoadScheduling() {
        String strDate =
                DateFormat.getInstance().format(DateSchedule);
        String[] thanhPhanNgay = strDate.split(" ");
        String date = thanhPhanNgay[0];
        String[] tokenDate = date.split("/");
        ArrayList<Scheduling> lstItem = SchedulingRepository.selectByDayMonthAndYear(Integer.parseInt(tokenDate[1]), Integer.parseInt(tokenDate[0]), Integer.parseInt(tokenDate[2]));
        model = new DefaultListModel();
        for (Scheduling cv : lstItem) {
            JLabel lb = new JLabel();
            lb.setFont(GlobalVariables.g_font);
            String pathImages;
            pathImages = System.getProperty("user.dir") + File.separator
                    + "src/Images/bell.png";

            ImageIcon imageIcon = new ImageIcon(pathImages);
            if (imageIcon.getIconWidth() > PREFERRED_SIZE || imageIcon.getIconHeight() > PREFERRED_SIZE) {
                imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(
                        PREFERRED_SIZE, PREFERRED_SIZE, Image.SCALE_SMOOTH));
            }

            lb.setIcon(imageIcon);
            lb.setName(String.valueOf(cv.getId()));
            lb.setText(cv.toString());
            model.addElement(lb);
        }
        lstSchedule.setModel(model);
        ListCellRenderer renderer = new MyImageListCellRenderer();
        lstSchedule.setCellRenderer(renderer);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jToolBar2 = new javax.swing.JToolBar();
        btnNew = new javax.swing.JButton();
        tooltrip_btnSave = new javax.swing.JButton();
        tooltrip_btnDelete = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstSchedule = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        txtHour = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtMinutes = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Tasks");

        jPanel1.setLayout(new java.awt.BorderLayout());

        jToolBar2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btnNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/001_01.gif"))); // NOI18N
        btnNew.setText("New");
        btnNew.setBorderPainted(false);
        btnNew.setFocusable(false);
        btnNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        jToolBar2.add(btnNew);

        tooltrip_btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/45.png"))); // NOI18N
        tooltrip_btnSave.setText("Save");
        tooltrip_btnSave.setBorderPainted(false);
        tooltrip_btnSave.setFocusable(false);
        tooltrip_btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tooltrip_btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tooltrip_btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tooltrip_btnSaveActionPerformed(evt);
            }
        });
        jToolBar2.add(tooltrip_btnSave);

        tooltrip_btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/001_29.png"))); // NOI18N
        tooltrip_btnDelete.setText("Delete");
        tooltrip_btnDelete.setBorderPainted(false);
        tooltrip_btnDelete.setFocusable(false);
        tooltrip_btnDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tooltrip_btnDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tooltrip_btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tooltrip_btnDeleteActionPerformed(evt);
            }
        });
        jToolBar2.add(tooltrip_btnDelete);

        jPanel1.add(jToolBar2, java.awt.BorderLayout.NORTH);

        jLabel3.setText("List Of Scheduling:");

        lstSchedule.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                lstScheduleMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(lstSchedule);

        jLabel4.setText("Hour:");

        jLabel5.setText("Minutes:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel3))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(txtHour, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(51, 51, 51)
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(txtMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(12, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtHour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-349)/2, (screenSize.height-289)/2, 349, 289);
    }// </editor-fold>//GEN-END:initComponents

    public boolean validateInputData(AtomicReference<Object> errText) {
        if (txtHour.getText().equals("")) {
            errText.set("Hour is empty");
            return false;
        }
        if (txtMinutes.getText().equals("")) {
            errText.set("Minute is empty");
            return false;
        }
        if (Integer.parseInt(txtHour.getText()) < 0 || Integer.parseInt(txtHour.getText()) > 24) {
            errText.set("Hour must in range (0 - 24)");
            return false;
        }
        if (Integer.parseInt(txtMinutes.getText()) < 0 || Integer.parseInt(txtMinutes.getText()) > 60) {
            errText.set("Minutes must in range (0 - 60)");
            return false;
        }
        return true;
    }

    private void tooltrip_btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tooltrip_btnSaveActionPerformed
        // TODO add your handling code here:
        AtomicReference<Object> errText = new AtomicReference<Object>("");
        if (!validateInputData(errText)) {
            JOptionPane.showMessageDialog(null, errText.get(),
                    "Announcement", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (SelectedSchedule == null) {
            Scheduling item = new Scheduling();
            item.setTime(Integer.parseInt(txtHour.getText()));
            item.setMinute(Integer.parseInt(txtMinutes.getText()));
            item.setDateschedule(DateSchedule);
            if (SchedulingRepository.insert(item)) {
                LoadScheduling();
                _Success = true;
                GlobalVariables.gSchedulings.put(String.valueOf(item.getId()), item);
            }
        } else {
            SelectedSchedule.setTime(Integer.parseInt(txtHour.getText()));
            SelectedSchedule.setMinute(Integer.parseInt(txtMinutes.getText()));
            if (SchedulingRepository.save(SelectedSchedule)) {
                LoadScheduling();
                _Success = true;
                GlobalVariables.gSchedulings.remove(String.valueOf(SelectedSchedule.getId()));
                GlobalVariables.gSchedulings.put(String.valueOf(SelectedSchedule.getId()), SelectedSchedule);
            }
        }
}//GEN-LAST:event_tooltrip_btnSaveActionPerformed

    private void tooltrip_btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tooltrip_btnDeleteActionPerformed
        // TODO add your handling code here:
        if (SelectedSchedule == null) {
            return;
        }
        if (SchedulingRepository.delete(SelectedSchedule.getId())) {
            LoadScheduling();
            txtHour.setText("");
            txtMinutes.setText("");
            _Success = true;
            GlobalVariables.gSchedulings.remove(String.valueOf(SelectedSchedule.getId()));
        }
}//GEN-LAST:event_tooltrip_btnDeleteActionPerformed

    private void lstScheduleMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstScheduleMousePressed
        // TODO add your handling code here:
        int modifiers = evt.getModifiers();
        if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
            if (evt.getClickCount() == 1) {
                if ((JLabel) lstSchedule.getSelectedValue() == null) {
                    return;
                }
                SelectedSchedule = SchedulingRepository.selectByID(Integer.parseInt(((JLabel) lstSchedule.getSelectedValue()).getName()));
                txtHour.setText(String.valueOf(SelectedSchedule.getTime()));
                txtMinutes.setText(String.valueOf(SelectedSchedule.getMinute()));
            }
        }
    }//GEN-LAST:event_lstScheduleMousePressed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        // TODO add your handling code here:
        SelectedSchedule = null;
        txtHour.setText("");
        txtMinutes.setText("");
    }//GEN-LAST:event_btnNewActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DlgAddSchedule dialog = new DlgAddSchedule(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnNew;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JList lstSchedule;
    private javax.swing.JButton tooltrip_btnDelete;
    private javax.swing.JButton tooltrip_btnSave;
    private javax.swing.JTextField txtHour;
    private javax.swing.JTextField txtMinutes;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the _Success
     */
    public boolean isAddSuccess() {
        return _Success;
    }
}
